package server

import (
	"context"
	"gitee.com/chunanyong/zorm"
	"gitee.com/xinshortlink/internal/pkg/mq"
	"net/http"
	"strconv"
	"time"

	"gitee.com/xinshortlink/api/xinshortlink/router"
	"gitee.com/xinshortlink/internal/pkg/conf"
	"go.uber.org/zap"
)

type Server struct {
	logger     *zap.Logger
	router     *router.Router
	httpServer *http.Server
	conf       *conf.Conf
	mq         mq.MQ
}

func NewServer(conf *conf.Conf, logger *zap.Logger, router *router.Router, dbDao *zorm.DBDao, mq mq.MQ) *Server {
	addr := ":" + strconv.Itoa(conf.Server.Port)

	return &Server{logger: logger, router: router, httpServer: &http.Server{
		Addr:         addr,
		Handler:      router.Engine,
		ReadTimeout:  time.Duration(conf.Server.ReadTimeout) * time.Millisecond,
		WriteTimeout: time.Duration(conf.Server.WriteTimeout) * time.Millisecond,
	}, conf: conf, mq: mq}
}

func (s *Server) Start() {
	err := s.httpServer.ListenAndServe()
	if err != nil {
		s.logger.Error("start http server error", zap.Error(err))
		panic(err)
	}

}

func (s *Server) Shutdown(ctx context.Context) error {
	s.mq.Shutdown()

	return s.httpServer.Shutdown(ctx)
}
